题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解析:
首先得明白平衡二叉树的定义,就是左右子树高度差的绝对值不超过1。
所以用递归可以解决,对二叉树进行左右遍历,然后得到左右子树的高度,判断绝对值的值是否大于1,然后一个节点的高度取决于return max(left_depth, right_depth);
代码:
int tryTree(TreeNode* curNode, int depth, bool &flag)
{
if (flag) return -1;
if (curNode == nullptr) return 0;
int left_depth = tryTree(curNode->left, depth, flag) + 1;
int right_depth = tryTree(curNode->right, depth, flag) + 1;
if (abs(left_depth - right_depth)>1) flag = true;
//cout << max(left_depth, right_depth) << endl;
return max(left_depth, right_depth);
}
bool IsBalanced_Solution(TreeNode* pRoot)
{
if (pRoot == nullptr) return true;
TreeNode* treeRoot = pRoot;
bool flag = false;
tryTree(treeRoot, 0, flag);
return !flag;
}
int main()
{
TreeNode* p1 = new TreeNode(1);
TreeNode* p2 = new TreeNode(2);
TreeNode* p3 = new TreeNode(3);
TreeNode* p4 = new TreeNode(4);
TreeNode* p5 = new TreeNode(5);
TreeNode* p6 = new TreeNode(6);
p1->left = p2;
p1->right = p3;
p2->left = p4;
p2->right = p5;
p5->left = p6;
p3->left = p3->right = nullptr;
p4->left = p4->right = nullptr;
p5->right = nullptr;
IsBalanced_Solution(p1);
return 0;
}
- Longest Valid Parentheses
Hard
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Example 2:
Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”
解析: 求最长的合法括号长度。我们分析下,就会知道,只有在出现“)”时,才会出现最长合法括号长度。
所以当为“("入栈它的序号(例如为5),当遇到第一个“)”(序号为6)时,就进行更新,找到最近的一组括号匹配,然后以6结尾的的最大合法长度为 2+ dp[4](以4结尾的最大合法长度)。
代码:
class Solution
{
public:
int longestValidParentheses(string s)
{
if(s.length()==0) return 0;
vector<int>dp(s.length(),0);
int max_length = -1;
stack<int>st;
for(int i=0;i<s.length();i++)
{
if(s[i]=='(') st.push(i);
else
{
if(!st.empty())
{
int top = st.top();
st.pop();
dp[i] = i - top + 1;
dp[i] += dp[top-1];
if(dp[i]>max_length) max_length = dp[i];
}
}
}
return max(max_length,0);
}
};